<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20" v-if="drawerVisible" style="margin-bottom: 15px;">
        <el-col :span="24">
          <div class="elInputM" style="display: inline-block;">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" :clearable="true" @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-button icon="el-icon-plus" type="primary" v-permission="permission.add" @click="addDialogVisibleShow">添加用户</el-button>
          <el-button icon="el-icon-edit" type="success" v-permission="permission.edit" @click="showEditDialog(handleCheckboxRows[0].id)" :disabled="handleCheckboxRows.length !== 1">修改</el-button>
          <el-button icon="el-icon-delete" type="danger" v-permission="permission.del" @click="deleteUserRows" :disabled="handleCheckboxRows.length < 1">删除</el-button>
        </el-col>
        <el-col :span="4" style="text-align: right;float: right;">
          <table-tools
            :drawerSearch="drawerVisible"
            @searchchange="searchChange"
            @refreshclick="refreshClick">
          </table-tools>
        </el-col>
      </el-row>

      <!-- 列表区域 -->
      <el-table
        :data="userList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        ref="table"
        max-height="520px"
        highlight-current-row
        border
        stripe
        header-row-class-name="el-table--small12"
        @sort-change="handleSortChange"
        style="width: 100%">
        <el-table-column type="selection" :selectable="checkboxT" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="username" label="账号" width="120"></el-table-column>
        <el-table-column prop="truename" label="全称" width="120"></el-table-column>
        <el-table-column prop="head_img" label="头像" width="120">
          <template v-slot="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 30px;height: 30px;"
                icon="el-icon-user-solid"
                size="30"
                :src="showImage(scope.row.head_img)"
                :preview-src-list="[showImage(scope.row.head_img)]">
                  <div slot="error" class="image-slot">
                    <el-avatar  shape="square" icon="el-icon-user-solid" :size="30"></el-avatar>
                  </div>
              </el-image>
            </div>
            <!-- <el-avatar  shape="square" icon="el-icon-user-solid" :size="30" :src="showImage(scope.row.head_img)"></el-avatar> -->
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="用户组" width="100" sortable="custom">
          <template v-slot="scope">
            <el-tag style="margin-right: 6px;" type="primary">{{scope.row.id !== 1 ? scope.row.adminRoleHasOne.name : '管理员'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="depart" label="部门" show-overflow-tooltip>
          <template v-slot="scope">
            {{scope.row.deptList.map(item => item.name).join()}}
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="频道" sortable="custom">
          <template v-slot="scope">
            {{scope.row.channelList.map(channel => channel.name).join()}}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="140"></el-table-column>
        <el-table-column prop="enable" label="状态" width="80" sortable="custom">
          <template v-slot="scope">
            <el-switch :disabled="scope.row.id === 1" v-permission="permission.edit" v-model="scope.row.enable" :active-value="2" :inactive-value="3" @change="userStateChanged(scope.row)" ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template v-slot="scope">
            <div v-if="scope.row.id !== 1">
                <el-tooltip v-permission="permission.edit" class="item" effect="dark" content="用户编辑" placement="top" :enterable="false">
                  <el-button type="primary" plain :id="scope.row.id" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
                </el-tooltip>
                <!-- 分配角色按钮 -->
                <el-tooltip v-permission="permission.edit" class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                  <el-button plain type="warning" :id="scope.row.id" icon="el-icon-setting" @click="giveRoleOpen(scope.row)"></el-button>
                </el-tooltip>
                <!-- 删除按钮 -->
                <el-button type="danger" v-permission="permission.del" plain :id="scope.row.id"  icon="el-icon-delete" @click="delUserDialog(scope.row.id)"></el-button>
            </div>
            <!-- 修改按钮 -->
           </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="480px"
        @close="addDilogClosed"
        :close-on-click-modal="false">
        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <div class="elInputS">
              <el-input placeholder="请输入" v-model="addForm.username"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="全称" prop="truename">
            <div class="elInputS">
              <el-input placeholder="请输入" v-model="addForm.truename"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <div class="elInputS">
              <el-input type="password" placeholder="请输入" v-model="addForm.password" autocomplete="off"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="确认密码" prop="chkpassword">
            <div class="elInputS">
              <el-input type="password" placeholder="请输入" v-model="addForm.chkpassword" autocomplete="off"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="所属部门" prop="depart">
            <div class="elInputM">
              <el-cascader
                  v-model="addForm.depart"
                  :options="departList"
                  :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                  clearable
                  style="width: 100%;">
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="所属频道" prop="channel">
            <div class="elInputM">
              <el-cascader
                  v-model="addForm.channel"
                  :options="channelList"
                  :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'channel_name' }"
                  clearable
                  style="width: 100%;">
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="所属用户组" prop="roleId">
            <div class="elInputM">
              <el-cascader
                  v-model="addForm.roleId"
                  :options="rolesList"
                  :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                  clearable
                  style="width: 100%;">
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <div class="elInputM">
              <el-input placeholder="请输入" v-model="addForm.email"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <div class="elInputM">
              <el-input placeholder="请输入" v-model="addForm.mobile"></el-input>
            </div>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户修改对话框 -->
      <el-dialog
        title="编辑用户信息"
        :visible.sync="editdialogVisible"
        width="480px"
        @close="editdialogClose"
        :close-on-click-modal="false">
        <el-form ref="editFormRef" :rules="editFormRules" :model="editForm" label-width="90px">
          <el-form-item label="用户名">
            <div class="elInputS">
              <el-input v-model="editForm.username" disabled=""></el-input>
            </div>
          </el-form-item>
          <el-form-item label="全称" prop="truename">
            <div class="elInputS">
              <el-input placeholder="请输入" v-model="editForm.truename"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <div class="elInputS">
              <el-input type="password" placeholder="请输入" v-model="editForm.password"  autocomplete="off"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="确认密码" prop="chkpassword">
            <div class="elInputS">
              <el-input type="password" placeholder="请输入" v-model="editForm.chkpassword" autocomplete="off"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="所属部门" prop="depart">
            <div class="elInputM">
              <el-cascader
                  v-model="editForm.depart"
                  :options="departList"
                  :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                  clearable
                  style="width: 100%;">
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="所属频道" prop="channel">
            <div class="elInputM">
              <el-cascader
                  v-model="editForm.channel"
                  :options="channelList"
                  :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'channel_name' }"
                  clearable
                  style="width: 100%;">
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="所属用户组" prop="roleId">
            <div class="elInputM">
              <el-cascader
                  v-model="editForm.roleId"
                  :options="rolesList"
                  :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                  clearable
                  style="width: 100%;">
              </el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <div class="elInputM">
              <el-input v-model="editForm.email" @input="change($event)"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <div class="elInputM">
              <el-input v-model="editForm.mobile" @input="change($event)"></el-input>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配用户角色"
        :visible.sync="giveRoledialogVisible"
        width="40%"
        @close="giveRoledialogClose"
        :close-on-click-modal="false">
        <p>当前的用户：{{this.userInfo.username}}</p>
        <p>当前所属角色：{{this.userInfo.adminRoleHasOne?this.userInfo.adminRoleHasOne.name:''}}</p>
        <el-select v-model="sureRole" placeholder="请选择角色">
          <el-option :value="0" label="请选择"></el-option>
          <el-option
            v-for="item in userRole"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="giveRoledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="giveRoleSure">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>

</template>

<script>
import tableTools from '@/components/tableToolsComponents' // tabs工具栏组件
export default {
  name: 'Users',
  components: {
    tableTools
  },
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (value == null || value === undefined) {
        return callback()
      }

      if (regEmail.test(value)) {
        // 合法的邮箱
        return callback()
      }

      return callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (value == null || value === undefined) {
        return callback()
      }

      if (regMobile.test(value)) {
        // 合法的手机号
        return callback()
      }

      return callback(new Error('请输入正确的手机号'))
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.addForm.chkpassword !== '') {
          this.$refs.addFormRef.validateField('chkpassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    var validateEditPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.editForm.chkpassword !== '') {
          this.$refs.editFormRef.validateField('chkpassword')
        }
        callback()
      }
    }
    var validateEditPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 指令权限
      permission: {
        add: ['admin', 'user::add'],
        edit: ['admin', 'user::edit'],
        del: ['admin', 'user::delete']
      },
      handleCheckboxRows: [], // table多选行数组
      drawerVisible: true, // 列表搜索栏显示状态
      loading: false, // 表格loading 状态
      // 获取用户列表参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示数目
        pagesize: 10,
        ordername: '',
        order: ''
      },
      userList: [],
      departList: [], // 部门列表
      channelList: [], // 频道列表
      rolesList: [],

      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户编辑对话框的显示与隐藏
      editdialogVisible: false,
      // 添加用户的表单数据
      addForm: {},
      // 用户编辑信息表单项
      editForm: {},
      editFormRules: {
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' } // 自定义手机号校验规则
        ],
        password: [
          { validator: validateEditPass, trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' }
        ],
        chkpassword: [
          { validator: validateEditPass2, trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' }
        ]
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' }
        ],
        chkpassword: [
          { validator: validatePass2, trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' }
        ],
        depart: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        channel: [
          { required: true, message: '请选择频道', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' } // 自定义邮箱校验规则
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' } // 自定义手机号校验规则
        ]
      },

      // 分配角色dialog 是否显示
      giveRoledialogVisible: false,

      // 需要被分配角色的用户信息
      userInfo: {},

      // 需要分配的角色菜单option
      userRole: {},

      // 当前分配的角色
      sureRole: null
    }
  },
  created() {
    console.log(this.isAdmin)
    this.getUserList()
    this.getRolesList()
    this.getChannelList()
    this.getDepartList()
  },
  methods: {
    async getUserList() {
      this.loading = true
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      // console.log(res, '**********')
      this.loading = false
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      console.log(res)
      this.$nextTick(() => {

      })
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 switch 开关状态的改变
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.enable}`)
      if (res.meta.status !== 200) {
        userinfo.enable = !userinfo.enable
        return this.$message.error(res.meta.message)
      }
      return this.$message.success('更新状态成功')
    },
    // 监听pagesize 改变的事件
    handleSizeChange(nesSize) {
      // console.log(nesSize)
      this.queryInfo.pagesize = nesSize
      this.getUserList()
    },
    // 监听 当前页码数改变事件
    handleCurrentChange(currPage) {
      this.queryInfo.pagenum = currPage
      this.getUserList()
      // console.log(currPage)
    },
    // 监听添加用户对话框的关闭事件
    addDilogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 监听table列表多选checkbox多选变化事件
    handleSelectionChange(select) {
      this.handleCheckboxRows = select || []
    },

    // 获取用户组列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles/list')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.rolesList = res.data
    },
    // 获取频道列表
    async getChannelList() {
      const { data: res } = await this.$http.get('channel/list', { params: { pagesize: 100 } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.channelList = res.data.list
      console.log(this.channelList)
    },
    // 获取部门列表
    async getDepartList() {
      const { data: res } = await this.$http.get('depts/list')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.departList = res.data
      console.log(this.departList)
    },
    // 添加用户dialog 显示
    addDialogVisibleShow() {
      this.addDialogVisible = true
    },
    // 点击按钮添加用户
    addUser() {
      // 表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 表示通过 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.data)
        }
        this.$message.success('新增成功')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    // 显示编辑用户修改的对话框
    async showEditDialog(id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }

      res.data.chkpassword = res.data.truepass
      res.data.password = res.data.truepass
      this.editForm = res.data
      // 编辑表单对象
      this.editForm.depart = Array.from(res.data.depart[0].split(','))
      this.editForm.channel = Array.from(res.data.channel[0].split(','))
    },
    // 监听修改用户对话框的关闭事件
    editdialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        console.log(this.editForm)
        if (!valid) return
        // 发起修改用户信息的请求
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          channel: this.editForm.channel,
          depart: this.editForm.depart,
          roleId: this.editForm.roleId,
          truename: this.editForm.truename,
          email: this.editForm.email,
          mobile: this.editForm.mobile,
          password: this.editForm.password
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.data)
        }
        // 关闭对话框
        this.editdialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('用户信息修改成功')
      })
    },

    // 批量删除用户
    async deleteUserRows() {
      const confirmresult = await this.$confirm('此操作将永久删除当前选中用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmresult !== 'confirm') {
        return this.$message.info('用户取消了删除')
      }

      const idarr = []
      this.handleCheckboxRows.map(item => {
        idarr.push(item.id)
      })

      const { data: res } = await this.$http.post('usersdels', {
        idstr: idarr.join()
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.$message.success('用户删除成功')
      // 刷新数据列表
      this.getUserList()
    },

    async delUserDialog(id) {
      const confirmresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmresult)
      if (confirmresult !== 'confirm') {
        return this.$message.info('用户取消了删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.$message.success('用户删除成功')
      // 刷新数据列表
      this.getUserList()
    },

    // 分配角色dialog 显示
    async giveRoleOpen(role) {
      console.log(role)
      this.userInfo = role
      const { data: res } = await this.$http.get('roles/list')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.sureRole = role.roleId
      this.userRole = res.data
      this.giveRoledialogVisible = true
    },
    // 分配角色 确定按钮事件
    async giveRoleSure() {
      // 表示通过 可以发起添加用户的网络请求
      const rolesData = { id: this.userInfo.id, roleId: this.sureRole }
      const { data: res } = await this.$http.post('users/roles', rolesData)

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }

      this.$message.success('修改成功')
      this.giveRoledialogVisible = false
      this.getUserList()
    },

    // 分配角色对话框关闭回调
    giveRoledialogClose() {
      this.sureRole = null
    },

    // 监听列表工具栏搜索点击触发
    searchChange(val) {
      this.drawerVisible = val
    },

    // 监听列表工具栏 刷新点击事件
    refreshClick() {
      this.getUserList()
    },
    showImage(url) {
      if (url) {
        return this.$fileserver + url
      }
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1
    },
    // 列表字段排序触发监听回调
    handleSortChange(column) {
      this.queryInfo.ordername = column.prop
      this.queryInfo.order = column.order
      console.log(column)
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
